/**
content:系统共用
author: hantian 
date:2013.10.30
*/

/*一些扩展*/
$.extend({
	/*doT模板引擎*/
	tmpl: function(template, data){
        return doT.template(template).apply(null,[data]);
	}
})
/* form validate*/
$.validate = (function(){
	/*默认设置*/
	var defaults = {
		tipsType:'ok_tip',
		/**
		 * 正则表达式集合
		 * @type {object}
		 * @description 键值对应表单元素的 type 或 v-type 属性
		 */
		regex: {
			email:		/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
			emails:		/^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*[,|\s]?)+$/,
			password:	/^[\w~!@#$%^&*]{6,32}$/,
			number:		/^-?([1-9]\d*|0(?!\.0+$))\.\d+?$/,
			url:		/^(http:\/\/)*[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
			// date:		/^\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}$/,
			username:	/^[0-9a-zA-Z_\u4E00-\u9FA5\\b]{1,14}$/,
			chinese:	/^[\u4E00-\u9FA5]+$/,
			phone:		/^(\d{4}|\d{3})-(\d{7,8})$/,
			mobile:		/^1\d{10}$/,
			licence:	/^(\d{18}|\d{15})$/
		}
	},
	/**
	 * 显示提示语
	 * @param {object} el  		[表单元素]
	 * @param {string} text		[提示语]
	 * @param {string} tipsType [提示方式]  ok_tip,error_tip;
	 */
	 showTips=function(el,text,tipsType){
	 	this.clearTips(el);
	 	if(text){
			var $tips = $('<span class="' + (tipsType||defaults.tipsType) + '"></span><span class="error_content">'+text+'</span>').insertAfter(el);	 		
	 	}else{
	 		var $tips = $('<span class="' + (tipsType||defaults.tipsType) + '"></span>').insertAfter(el);
	 	}
		return $tips;
	 },
	 clearTips = function(el){
		$(el).parent().find('.ok_tip,.error_tip,.error_content').remove();
	},
	/*格式错误*/
	isWrong =  function(el,regex){
		regexString=defaults.regex[regex];
		regexNew = new RegExp(regexString);
		return regexNew.test(el.value)?false:true;
	},
	/**
	 * 必填项为空
	 * @param	{object}  el    [表单元素]
	 * @return	{boolean} true  [已填]
	 * 			{boolean} false [未填]
	 */
	isEmpty = function(el){
		var value = el.value, type = el.type;
		if('password'!==type){
			value = $.trim(value);
		}
		if('checkbox'===type){
			value = el.checked;
		}
		return ('string' === typeof el.getAttribute('required') && !value);
	};
	return {
		showTips   : showTips,
		clearTips  : clearTips,
		isEmpty   : isEmpty,
		isWrong   : isWrong
	};
})();

//*系统共用*/
$.sys={
	/**
	 * 获取表单数据
	 * @param  {string} form_name [表单name]
	 * @return {json}   [ajax data]
	 * @author hantian
	 */
	get_form_data: function(form_name){
		var form     = document.forms[form_name],
			elements = form.elements,
			length   = elements.length,
			params   = {};
		for(var i=0; i<length; i++){
			if(elements[i].disabled==true){
				continue;
			}
			var name  = elements[i].name,
				value = elements[i].value,
				type  = elements[i].type;
			if(name && type){
				type = type.toLowerCase();
				if(type=='checkbox'){
					if(!elements[i].checked){
						value = '';
					}
				}else if(type=='radio'){
					if(!elements[i].checked){
						continue;
					}
				}else{
					var txt_tip = elements[i].getAttribute('txt-tip');
					if(txt_tip && txt_tip==value){
						value = '';
					}
				}
				params[name] = encodeURIComponent(value);
			}
		}
		var fm_action = form.getAttribute('action') || '',
			fm_method = form.getAttribute('method') || 'POST',
			fm_params = params;
		return {action:fm_action,method:fm_method,params:fm_params};
	},
	/*表单提交插件*/
	ajax:{
		form_submit:function(form_name,callback){
			var fm_data = $.sys.get_form_data(form_name);
			var form    = document.forms[form_name];
			$.ajax({
				type	:	fm_data['method'],
				url	:	fm_data['action'],
				data	:  	 $(form).serialize(),
				dataType:	"json",
				success	:	callback
			});
		}
	},
	/*form下的一些公共插件*/
	form:{
		/*ie10 以下支持占位符*/
		placeholder:function(){
			/*如果浏览器不支持*/
			if( !('placeholder' in document.createElement('input')) ){
				// $('input[placeholder], textarea[placeholder]').each(function(){
				// 	var placeholder = $(this).attr("placeholder"),
				// 		css         = this.currentStyle,
				// 		width       = css.width,
				// 		height      = css.height,
				// 		paddingLeft = css.paddingLeft,
				// 		paddingTop  = css.paddingTop,
				// 		paddingBottom = css.paddingBottom,
				// 		paddingRight = css.paddingRight,
				// 		marginLeft 	= css.marginLeft,
				// 		marginTop   = css.marginTop,
				// 		lineHeight  = css.lineHeight,
				// 		background  = css.backgroundColor,
				// 		textintend  = css.textIndent,
				// 		fontsize 	= css.fontSize,
				// 		$this       = $(this);
				// 		$this.before('<div class="placeholder" style="z-index:9;position:absolute;top:0;left:0;font-size:'+fontsize+'"><span style="display:block;color:#666;margin-left:'+marginLeft+';margin-top:'+marginTop+';text-indent:'+textintend+';line-height:'+lineHeight+';width:'+width+';height:'+height+';">'+placeholder+'</span></div>')
				// 			.on('keyup',function(){
				// 				if(this.value){
				// 					$this.prev().hide();
				// 				}else{
				// 					$this.prev().show();
				// 				}
				// 			})
				// 		this.onpropertychange=function(){
				// 			if($this[0].value){
				// 				$this.prev().hide();
				// 			}else{
				// 				$this.prev().show();
				// 			}
				// 		}
				// 		$this.prev().on('click',function(){
				// 			$this.focus();
				// 		})
				// 		if($this[0].value){
				// 			$this.prev().hide();
				// 		}else{
				// 			$this.prev().show();
				// 		}
				// });
				$('input[placeholder], textarea[placeholder]').each(function () {
                    var obj = $(this);
					if(navigator.appVersion.match(/8./i)=='8.'&&obj.attr('type') == 'password'){
						return;
					} 

                    if (obj.attr('placeholder') != '') {
                        obj.addClass('IePlaceHolder');

                        if ($.trim(obj.val()) == '') {
                        	if(obj.attr('type') == 'password'){
                        		obj.attr('type',"text");
                        		obj.attr('origin',"password");
                        	}
                            obj.val(obj.attr('placeholder'));
                        }
                    }
                });

                $('.IePlaceHolder').focus(function () {
                    var obj = $(this);
                    if (obj.val() == obj.attr('placeholder')) {
                        obj.val('');
                        if(obj.attr('origin')=="password"){
                        	obj.attr('type',"password");
                        }
                    }
                });

                $('.IePlaceHolder').blur(function () {
                    var obj = $(this);
                    if ($.trim(obj.val()) == '') {
                    	if(obj.attr('origin')=="password"){
                        	obj.attr('type',"text");
                        }
                        obj.val(obj.attr('placeholder'));
                    }
                });

			}
		}
	},
	/*ajax等待操作，防止误操作*/
	loading : function(){
		$.blockUI({ //当点击事件发生时调用弹出层

 			message: '<img src="/static/img/publicloading7.gif"/>', //要弹出的元素box

 			css: { //弹出元素的CSS属性

			top: '50%',

        	left: '50%',

        	textAlign: 'left',

        	marginLeft: '-50px',

        	marginTop: '-50px',

 			width: '100px',

 			background: '#fff',

 			cursor: 'wait',

 			border : "none"

 			}
 		});	
	},
	/*loading结束*/
	loading_end:function(){
		$.unblockUI();
	},
	/**
	*弹出框
	*@param msg 提示的信息
	**/
	alert : function(msg){
		var $div = '<div class="alert_div">\
				<div class="alert_head">\
				<span class="alert_close"></span>\
				<span class="alert_title">提示</span>\
				</div>\
				<div class="alert_body">\
				<span class="alert_message">'+msg+'</span>\
				</div>\
				<div class="alert_foot">\
				<a href="javascript:void(0);" class="alert_btn">确定</a>\
				</div>\
				</div>\
				<div class="mark_div"></div>',
			$alert_div = $(".alert_div"),
			//蒙层
			$mark_div = $(".mark_div");
			var mark_hight = (document.body.clientHeight>document.body.scrollHeight?document.body.clientHeight:document.body.scrollHeight);
			 
			//判断是否已经添加
			if($alert_div.length>0){
				$alert_div.find(".alert_message").text(msg);
				//显示蒙层
				$mark_div.show();
				$alert_div.show();
			}else{
				$("body").append($div);
				$(".mark_div").css("height",mark_hight);
			}
			
			$(".alert_div").on("click",".alert_btn,.alert_close",function(){
				$(".alert_div").hide();
				$(".mark_div").hide();
			});
		}
}

$(document).ready(function(){
	/*占位符*/
	$.sys.form.placeholder();
})

jQuery.fn.isChildAndSelfOf = function(b){//判断元素是否是目标元素的子元素或自己本身
    return (this.closest(b).length > 0);
};
jQuery.fn.isChildOf = function(b){
return (this.parents(b).length > 0);
};
/*获取参数*/
(function($){
	$.getUrlParam = function(name)
	{
		
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = decodeURI(window.location.search).substr(1).match(reg);
	if (r!=null) return unescape(r[2]); return null;
	}
})(jQuery);


$(document).ready(function(){
	//for ie
	if(document.all){
	    $('input[type="text"]').each(function() {
	        var that=this;

	        if(this.attachEvent) {
	            this.attachEvent('onpropertychange',function(e) {
	                if(e.propertyName!='value') return;
	                $(that).trigger('input');
	            });
	        }
	    })
	}
})


/*!
 * jquery.hash.js
 * @author ydr.me
 * @version 1.1
 */
!function(r,t){function e(n){return"string"==r.type(n)||"number"==r.type(n)}function o(n){return e(n)?encodeURIComponent(n):n}function a(n){return e(n)?decodeURIComponent(n):n}function s(n,r){for(var t in n)if(n[t]==r[t])return!1;return!0}function h(n,r){for(var t in n)if(n[t]!=r[t])return!0;return!1}function u(n){var r={},t="!";if(n=(n.match(/#([^#]*)$/)||["",""])[1],""===n)return r;switch(n=n.replace(/^.*([!\?])/,"$1"),t=n.charAt(0),"!"!=t&&"?"!=t&&(t=g.hashType),n=n.replace(/^[!\?]*/,""),n=n.replace(/^[\/&]*|[\/&]*$/g,""),t){case"!":r=c(n),g.hashType="!";break;case"?":r=l(n),g.hashType="?";break;default:r[n]="",g.hashType="!"}return r}function c(n){for(var t,o=n.split("/"),a={},i=[],s=[],h=!1,u=0,c=o.length;c>u;u++)t=r.trim(o[u]),e(t)&&""!==t&&(h?s.push(t):i.push(t),h=!h);for(u=0,c=i.length;c>u;u++)a[i[u]]=s[u];return a}function l(n){for(var r,e,o,i=n.split("&"),s={},h=0,u=i.length;u>h;h++)r=i[h].split("="),e=a(r[0]),o=r[1]===t?"":a(r[1]),""!==e&&e!==t&&(s[e]=o);return s}function f(n){var r,t=[];for(r in n)t.push(o(r)+"/"+o(n[r]));return"!"+t.join("/")}function p(n){var r,t=[];for(r in n)t.push(o(r)+"="+o(n[r]));return"?"+t.join("&")}function d(n,r){for(var t in r)e(t)&&e(r[t])&&(n[t]=r[t]);switch(g.hashType){case"!":default:strHash=f(n);break;case"?":strHash=p(n)}return window.location.hash=strHash,strHash}function w(n,r){for(var t=0,o=r.length;o>t;t++)e(r[t])&&delete n[r[t]];switch(g.hashType){case"!":default:strHash=f(n);break;case"?":strHash=p(n)}return window.location.hash=strHash,strHash}function y(t,e,o,a){var c,l={type:e,key:o,fn:a};T.push(l),c=function(){var e=window.location.hash;for(objNow=u(e),objOld={},objNew={},i=0,j=0,m=0,n=0,l={},o=[],r.isEmptyObject(b)&&(b=t),t=b,b=objNow,i=0,j=T.length;j>i;i++){for(l=T[i],o=l.key,a=l.fn,objOld={},objNew={},m=0,n=o.length;n>m;m++)objOld[o[m]]=t[o[m]],objNew[o[m]]=objNow[o[m]];"and"==l.type?s(objOld,objNew)&&a(t,objNow):h(objOld,objNew)&&a(t,objNow)}},v||(v=1,window.addEventListener("hashchange",c,0))}var b={},g={hashType:"!"},v=0,T=[];r.extend({hash:function(){var n,t,o,a=arguments,i=arguments.length,s=window.location.hash,h={},c={},l={};if(0==i)return u(s);if(1==i&&e(a[0]))return h=u(s),h[a[0]];if(1==i&&"array"==r.type(a[0])){for(h=u(s),t=a[0].length,n=0;t>n;n++)o=a[0][n],c[o]=h[o];return c}return 2==i&&e(a[0])&&e(a[1])?(h=u(s),l[a[0]]=a[1],d(h,l)):3==i&&e(a[0])&&e(a[1])&&"string"==r.type(a[2])?(h=u(s),l[a[0]]=a[1],g.hashType=a[2],d(h,l)):1==i&&"object"==r.type(a[0])?(h=u(s),d(h,a[0])):2==i&&"object"==r.type(a[0])&&"string"==r.type(a[1])?(h=u(s),g.hashType=a[1],d(h,a[0])):2==i&&e(a[0])&&null===a[1]?(h=u(s),w(h,[a[0]])):2==i&&r.isArray(a[0])&&null===a[1]?(h=u(s),w(h,a[0])):1==i&&null===a[0]?(o=r(window).scrollTop(),window.location.hash="",r(window).scrollTop(o),""):void(3==i&&"listen"===a[0]&&e(a[1])&&r.isFunction(a[2])?(h=u(s),y(h,"and",[a[1]],a[2])):3==i&&"listenAnd"===a[0]&&r.isArray(a[1])&&r.isFunction(a[2])?(h=u(s),y(h,"and",a[1],a[2])):3==i&&"listenOr"===a[0]&&r.isArray(a[1])&&r.isFunction(a[2])&&(h=u(s),y(h,"or",a[1],a[2])))}}),r.hash.defaults=g}(jQuery);

/*------------------------------------------------------------------------------
*插件名称：图片自适应容器大小插件
*调用方式：$(selector).resizeImg({w:maxWidth,h:maxHeight})
--------------------------------------------------------------------------------
*/

(function($){

 $.fn.extend({

	resizeImg:function(opt,callback){

		var defaults={w:200,h:150};

		var opts = $.extend(defaults, opt);

		  this.each(function(){

		    $(this).load(function(){

		    var imgWidth=this.width,imgHeight=this.height;

		    if(imgWidth>opts["w"]){

				  this.width=opts["w"];

				  this.height=imgHeight*(opts["w"]/imgWidth);

				  imgWidth=opts["w"];

				  imgHeight=this.height;

		  }

		if(imgHeight>opts["h"]){

		this.height=opts["h"];

		this.width=imgWidth*(opts["h"]/imgHeight);

		imgHeight=opts["h"];

		imgWidth=this.width;

		}

		//水平居中，垂直居中

		$(this).css({"margin-top":(opts["h"]-imgHeight)/2,"margin-left":(opts["w"]-imgWidth)/2});

		});

		});
	         }
	   });
 })(jQuery);
